package com.yc.io.netty.demo1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.logging.Logger;

/**
 * Created by Administrator on 2017/5/17. 用于对网络事件进行读写操作
 */
public class TimeClientHandler extends ChannelInboundHandlerAdapter {
	private static final Logger logger = Logger.getLogger(TimeClientHandler.class.getName());

	/**
	 * 当客户端和服务端 TCP 链路建立成功之后，Netty 的 NIO 线程会调用 channelActive 方法
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		String reqMsg = "我是客户端 " + Thread.currentThread().getName();
		byte[] reqMsgByte = reqMsg.getBytes("UTF-8");
		ByteBuf reqByteBuf = Unpooled.buffer(reqMsgByte.length);
		/**
		 * writeBytes：将指定的源数组的数据传输到缓冲区 调用 ChannelHandlerContext 的 writeAndFlush
		 * 方法将消息发送给服务器
		 */
		reqByteBuf.writeBytes(reqMsgByte);
		ctx.writeAndFlush(reqByteBuf);
	}

	/**
	 * 当服务端返回应答消息时，channelRead 方法被调用，从 Netty 的 ByteBuf 中读取并打印应答消息
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf buf = (ByteBuf) msg;
		byte[] req = new byte[buf.readableBytes()];
		buf.readBytes(req);
		String body = new String(req, "UTF-8");
		System.out.println(Thread.currentThread().getName() + ",Server return Message：" + body);
		ctx.close();
	}

	/**
	 * 当发生异常时，打印异常 日志，释放客户端资源
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		/** 释放资源 */
		logger.warning("Unexpected exception from downstream : " + cause.getMessage());
		ctx.close();
	}
}
